#!/usr/bin/env bash
# encoding: utf-8
# Date: 2022-08
# Desc: 基于 easyrsa3 的 OpenVPN 客户端证书的创建和销毁
#       注意，证书密码中强烈建议别有$符号！
# 


cmd="$1"
username="$2"
user_passwd="Kongfz.com_202208"
password=$(cat /etc/openvpn/auth |sed 's/\$/\\\\\\$/g')

print() { printf "%s\n" "$*"; }

die() {
    print "
Easy-RSA error:

$1" 1>&2
    exit ${2:-1}
}

generate() {
# 生成证书
cd /etc/openvpn/easy-rsa/3/
/bin/expect <<-EOF
spawn ./easyrsa build-client-full ${username} nopass
expect "Enter pass phrase for /etc/openvpn/easy-rsa/3/pki/private/ca.key:"
send "auth-passwd\n"
expect eof
EOF

    # 证书打包
    if [ -f "/etc/openvpn/easy-rsa/3/pki/issued/${username}.crt" ]
    then
        mkdir -p /tmp/${username}/tmp
        cp -ra /etc/openvpn/easy-rsa/3/pki/ca.crt /etc/openvpn/easy-rsa/3/pki/ta.key /etc/openvpn/easy-rsa/3/pki/issued/${username}.crt /etc/openvpn/easy-rsa/3/pki/private/${username}.key /tmp/${username}/tmp/
        cp /data/backup/client.ovpn /tmp/${username}/tmp
        sed -i "s/kongfz.com_yangqi/${username}/g" /tmp/${username}/tmp/client.ovpn

        mkdir -p /tmp/${username}/config
        mv /tmp/${username}/tmp/*.* /tmp/${username}/config/
        cd /tmp/
        tar czvf ${username}.tar.gz ${username}/config/*
        rm -rf /tmp/${username}


        # 添加账号密码 /etc/openvpn/psw-file
        if [ "x$(grep ${username} /etc/openvpn/psw-file)" == "x" ]
        then
            echo "no such and to add" ;
            echo "${username} ${user_passwd}" >> /etc/openvpn/psw-file
        else
            echo "exist";
        fi
    else
        die "证书生产失败！！！"
    fi
}



revoke() {
    cd /etc/openvpn/easy-rsa/3
/bin/expect <<-EOF
spawn /etc/openvpn/easy-rsa/3/easyrsa revoke ${username}
expect "revocation:"
send "yes\r"
expect "Enter pass phrase for /etc/openvpn/easy-rsa/3/pki/private/ca.key:"
send "auth-passwd\n"
expect eof
EOF

/bin/expect <<-EOF
spawn /etc/openvpn/easy-rsa/3/easyrsa gen-crl
expect "Enter pass phrase for /etc/openvpn/easy-rsa/3/pki/private/ca.key:"
send "auth-passwd\n"
expect eof
EOF

# 再次确认证书状态 V为可用状态，R为已回收状态
grep ${username} /etc/openvpn/easy-rsa/3/pki/index.txt
}

restart_vpn() {
    systemctl restart openvpn@server.service
}


# Main Entrance
case "$cmd" in
    add)
        generate
        restart_vpn
        ;;
    revoke)
        revoke
        restart_vpn
        ;;
    *)
        die "Unknown command '$cmd'. Run without commands for usage help."
        ;;
esac